package com.citydo.webrtcspringboot.websocket.stream;

import java.util.HashMap;
import java.util.Map;

public class ActionManager {
    //有返回值接口
    private final Map<FuncName, Func<Object>> funcMap = new HashMap<>();
    //无返回值接口
    private final Map<ActionName, Action<Object>> actionMap = new HashMap<>();
    private static ActionManager _instance = null;

    //单例
    public static ActionManager Instance() {
        if (_instance == null)
            _instance = new ActionManager();
        return _instance;
    }

    public ActionManager() {
    }

    private Map<FuncName, Func<Object>> getFuncMap() {
        return funcMap;
    }

    public Map<ActionName, Action<Object>> getActionMap() {
        return actionMap;
    }

    //添加事件
    public void addEvent(FuncName key, Func<Object> func) {
        if (!getFuncMap().containsKey(key))
            getFuncMap().put(key, func);
    }

    //添加事件
    public void addEvent(ActionName key, Action<Object> action) {
        if(!getActionMap().containsKey(key))
            getActionMap().put(key, action);
    }

    //示例
    public void test(FuncName key) {
        //添加事件
        ActionManager.Instance().addEvent(key, new Func<Object>() {
            @Override
            public Object invoke(Object... params) {
                return "示例";
            }
        });
        //lambda表达式
        ActionManager.Instance().addEvent(key, params -> {
            return "示例";
        });
        //lambda简写
        ActionManager.Instance().addEvent(key, params -> "示例");
        //调用
        ActionManager.Instance().invoke(key);
        //调用无返回值委托方法
        ActionManager.Instance().addEvent(ActionName.TEST, params -> method());
    }

    public void method() {
    }

    //执行方法
    public Object invoke(FuncName key, Object... params) {
        if (getFuncMap().containsKey(key))
            return getFuncMap().get(key).invoke(params);
        else
            return null;
    }

    //执行无返回值方法
    public void invoke(ActionName key, Object... params) {
        if (getActionMap().containsKey(key))
            getActionMap().get(key).invoke(params);
    }

    public interface Func<T> {
        T invoke(T... params);
    }

    public interface Action<T> {
        void invoke(T... params);
    }

    public enum ActionName {TEST, userEntryNotice}

    public enum FuncName {chooseServer}
}
